<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="text item">
        <div>
          <el-alert
            show-icon
            title="未找到当前工单流程信息，请确认当前工单绑定的流程是否存在。"
            type="warning"
          />
          <div>
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                更新频率<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="10000">10秒</el-dropdown-item>
                <el-dropdown-item command="30000">30秒</el-dropdown-item>
                <el-dropdown-item command="60000">60秒</el-dropdown-item>
                <el-dropdown-item command="120000">120秒</el-dropdown-item>
                <el-dropdown-item command="360000">360秒</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 15px">
      <div slot="header" class="clearfix">
        <span>工单信息</span>
      </div>
      <div class="text item">
        <el-form label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="标题:" style="margin-bottom: 5px">
                <span>{{ taskList.name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批情况:" style="margin-bottom: 0">
                <span v-if="taskList.status==='not_start_approve'">
                  <el-tag type="primary">还未开始审批</el-tag>
                </span>
                <span v-if="taskList.status==='approveing'">
                  <el-tag type="info">审批中</el-tag>
                </span>
                <span v-else-if="taskList.status==='ok_approved'">
                  <el-tag type="success">审批通过</el-tag>
                </span>
                <span v-else-if="taskList.status==='fail_approve'">
                  <el-tag type="danger">审批不通过</el-tag>
                </span>
                <span v-else-if="['not_start_exec','progressing','fail','timeout','success'].includes(taskList.status)">
                  <el-tag type="success">审批通过</el-tag>
                </span>
                <span v-else>
                  <el-tag type="success">未知状态</el-tag>
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span>任务信息</span>
      </div>
      <div class="text item">
        <el-form label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="任务名称:" style="margin-bottom: 5px">
                <span>{{ taskList.name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务状态:" style="margin-bottom: 5px">
                <span v-if="taskList.status==='not_start_approve'">
                  <el-tag type="primary">还未开始审批</el-tag>
                </span>
                <span v-if="taskList.status==='approveing'">
                  <el-tag type="info">审批中</el-tag>
                </span>
                <span v-else-if="taskList.status==='ok_approved'">
                  <el-tag type="success">审批通过</el-tag>
                </span>
                <span v-else-if="taskList.status==='fail_approve'">
                  <el-tag type="danger">审批不通过</el-tag>
                </span>
                <span v-else-if="taskList.status==='not_start_exec'">
                  <el-tag type="warning">任务还未开始</el-tag>
                </span>
                <span v-else-if="taskList.status==='progressing'">
                  <el-tag type="warning">任务执行中</el-tag>
                </span>
                <span v-else-if="taskList.status==='fail'">
                  <el-tag type="danger">任务执行失败</el-tag>
                </span>
                <span v-else-if="taskList.status==='timeout'">
                  <el-tag type="warning">任务已超时</el-tag>
                </span>
                <span v-else-if="taskList.status==='success'">
                  <el-tag type="success">任务执行成功</el-tag>
                </span>
                <span v-else>
                  <el-tag type="success">未知状态</el-tag>
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属项目:" style="margin-bottom: 5px">
                <span>{{ taskList.project_st }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属环境:" style="margin-bottom: 5px">
                <span>{{ taskList.env }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建用户:" style="margin-bottom: 5px">
                <span>{{ taskList.create_user_st }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间:" style="margin-bottom: 5px">
                <span>{{ taskList.create_time }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务时间:" style="margin-bottom: 5px">
                <span>{{ taskList.task_time }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完成时间:" style="margin-bottom: 5px">
                <span>{{ taskList.finish_time }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注:" style="margin-bottom: 5px">
                <span>{{ taskList.note }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span>操作列表</span>
      </div>
      <div class="text item">
        <el-collapse accordion>
          <template v-for="data in subTaskList">
            <el-collapse-item :key="data.id">
              <template slot="title">
                <el-form label-width="100px" size="medium" inline>
                  <el-row>
                    <el-col>
                      <el-form-item label="子任务:" style="margin-bottom: 5px">
                        <span style="line-height: 50px">{{ data.container }}</span>
                      </el-form-item>
                      <el-form-item label="状态" style="margin-bottom: 5px">
                        <span v-if="data.status==='not_start_exec'" style="line-height: 50px">
                          <el-tag type="warning">任务还未开始</el-tag>
                        </span>
                        <span v-else-if="data.status==='progressing'" style="line-height: 50px">
                          <el-tag type="warning">任务执行中</el-tag>
                        </span>
                        <span v-else-if="data.status==='fail'" style="line-height: 50px">
                          <el-tag type="danger">任务执行失败</el-tag>
                        </span>
                        <span v-else-if="data.status==='success'" style="line-height: 50px">
                          <el-tag type="success">任务执行成功</el-tag>
                        </span>
                        <span v-else style="line-height: 50px">
                          <el-tag type="success">未知状态</el-tag>
                        </span>
                      </el-form-item>
                      <el-form-item label="创建时间" style="margin-bottom: 5px">
                        <span style="line-height: 50px">{{ data.create_time }}</span>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>
              <el-table
                :key="tableKey"
                v-loading="listLoading"
                :data="data.exec_list"
                border
                fit
                max-height="250px"
                highlight-current-row
                style="width: 100%;"
                @sort-change="sortChange"
              >
                <el-table-column label="操作ID" align="center">
                  <template slot-scope="{row}">
                    <span class="link-type">{{ row.id }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                  <template slot-scope="{row}">
                    <span v-if="row.status==='not_start_exec'">
                      <el-tag type="warning">任务还未开始</el-tag>
                    </span>
                    <span v-else-if="row.status==='progressing'">
                      <el-tag type="warning">任务执行中</el-tag>
                    </span>
                    <span v-else-if="row.status==='fail'">
                      <el-tag type="danger">任务执行失败</el-tag>
                    </span>
                    <span v-else-if="row.status==='recover_not_start_exec'">
                      <el-tag type="warning">回档还未开始</el-tag>
                    </span>
                    <span v-else-if="row.status==='recover_progressing'">
                      <el-tag type="warning">回档执行中</el-tag>
                    </span>
                    <span v-else-if="row.status==='recover_success'">
                      <el-tag type="success">回档执行成功</el-tag>
                    </span>
                    <span v-else-if="row.status==='recover_fail'">
                      <el-tag type="danger">回档执行失败</el-tag>
                    </span>
                    <span v-else-if="row.status==='success'">
                      <el-tag type="success">任务执行成功</el-tag>
                    </span>
                    <span v-else>
                      <el-tag type="success">未知状态</el-tag>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center">
                  <template slot-scope="{row}">
                    <span class="link-type">{{ row.create_time }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="完成时间" align="center">
                  <template slot-scope="{row}">
                    <span class="link-type">{{ row.finish_time }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="参数" align="center">
                  <template slot-scope="{row}">
                    <span class="link-type">{{ row.params }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="输出信息" align="center">
                  <template slot-scope="{row}">
                    <span class="link-type">{{ row.output }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </template>
        </el-collapse>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 15px">
      <div slot="header" class="clearfix">
        <span>任务日志</span>
      </div>
      <div class="text item">
        <el-scrollbar style="height:300px">
          <el-timeline :reverse="reverse">
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="activity.timestamp"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-scrollbar>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getTasks, updateTask, deleteTask, get_exec_logs
} from '@/api/task'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'ComplexTable',
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      taskList: [],
      subTaskList: [],
      activities: [],
      reverse: true,
      timer: null,
      total: 0,
      post: null,
      parent: [],
      listLoading: true,
      listTaskQuery: {
        id: this.$route.query.task_id
      },
      listTaskLogQuery: {
        page: 1,
        limit: 10,
        sort: '+id',
        task: this.$route.query.task_id
      },
      sortOptions: [{
        label: 'ID 正序', key: '+id'
      }, {
        label: 'ID 逆序', key: '-id'
      }],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改权限',
        create: '添加权限'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        path: [{
          required: true, message: '资源路径必须填写!', trigger: 'blur'
        }],
        name: [{
          required: true, message: '权限名称必须填写！', trigger: 'blur'
        }],
        model: [{
          required: true, message: '资源必须填写！', trigger: 'blur'
        }],
        level: [{
          required: true, message: '菜单级别必须填写！', trigger: 'blur'
        }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getTask()
    this.handleLogs()
  },
  methods: {
    buttonStatus(data, button) {
      if (data === undefined || data.length <= 0) {
        return false
      } else {
        return data.includes(button)
      }
    },
    handleCommand(command) {
      this.flushTime = command
      this.$message(' 更新频率：' + command / 1000 + '秒')
      this.refreshTable(command)
    },
    refreshTable(command = 1000) {
      clearInterval(this.timer)
      this.timer = null
      this.timer = setInterval(() => {
        // 需要做的事情
        console.log('更新频率:' + command / 1000 + '秒')
        this.getTask()
        this.handleLogs()
      }, command)
      this.$once('hook:beforeDestroy', () => {
        clearInterval(this.timer)
        // eslint-disable-next-line no-const-assign
        this.timer = null
      })
    },
    getTask() {
      this.listLoading = true
      // 重置选择上的空
      if (this.listTaskQuery.level === '') {
        this.listTaskQuery.level = undefined
      }
      getTasks(this.listTaskQuery).then(response => {
        const { data, total, meta } = response
        const { post_tag } = meta
        this.taskList = data[0]
        this.total = total
        this.post = post_tag
        const { sub_task_st } = this.taskList
        this.subTaskList = sub_task_st

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.getTask()
    },
    handleLogs() {
      this.drawer = true
      this.activities = []
      get_exec_logs(this.listTaskLogQuery).then(response => {
        const { data } = response
        data.map(item => {
          this.activities.push({
            content: item.log,
            timestamp: item.create_time
          })
        })
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {
        prop, order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateTask(tempData.id, tempData).then(response => {
            const { meta } = response
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.$notify({
              title: '成功',
              message: meta.msg,
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      deleteTask(row.id).then(response => {
        const { meta } = response
        const index = this.list.findIndex(v => v.id === this.temp.id)
        this.list.splice(index, 1)
        this.$notify({
          title: '成功',
          message: meta.msg,
          type: 'success',
          duration: 2000
        })
        this.handleFilter()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
